#include "msghttp.h"

int main(int argc, char const *argv[])
{
    int serversocket = ininit_socket(atoi(argv[1]));
    fd_set readfds, tmpfds;
    FD_ZERO(&readfds);
    FD_ZERO(&tmpfds);
    int maxfds = serversocket;
    FD_SET(0, &readfds);
    FD_SET(serversocket, &readfds);
    struct timeval tval;
    tval.tv_usec = 1000;
    char buffer[MSG_LENGTH] = {0};
    while (1)
    {
        tmpfds = readfds;
        select(maxfds + 1, &tmpfds, NULL, NULL, &tval);
        if (FD_ISSET(serversocket, &tmpfds))
        {
            int clientsockfd = accept(serversocket, NULL, NULL);
            if (clientsockfd < 0)
            {
                perror("accepting failed");
                return -1;
            }
            FD_SET(clientsockfd, &readfds);
            if (maxfds < clientsockfd)
                maxfds = clientsockfd;
        }
        for (int i = 4; i <= maxfds; i++)
        {
            if (FD_ISSET(i, &tmpfds))
            {
                int result = recv(i, buffer, sizeof(buffer), 0);
                if (result < 0)
                {
                    perror("recving failed");
                    return -1;
                }
                else if (result == 0)
                {
                    puts("client exited");
                    close(i);
                    FD_CLR(i, &readfds);
                    if (i == maxfds)
                        maxfds--;
                }
                else
                {
                    char *tmp = strchr(buffer, '\n');
                    *tmp = 0;
                    int flag = -1;
                    // puts(buffer);
                    void *arg = message_handler(buffer, &flag);
                    if (arg == NULL)
                    {
                        return -1;
                    }
                    if (flag == GET)
                    {
                        struct get_header *header = (struct get_header *)arg;
                        // puts(buffer);
                        // puts(header->page);
                        get_handler(i, header);
                    }
                    else if (flag == POST)
                    {
                        struct post_header *header = (struct post_header *)arg;
                        // puts(header->page);
                        char *pr = strstr(tmp + 1, "\r\n\r\n");
                        pr += 2;
                        init_post_par(header, pr);
                        post_handler(i, header);
                    }
                    close(i);
                    if (i == maxfds)
                        maxfds--;
                }
            }
        }
    }
    return 0;
}
